import React from "react";
import { Image, LayoutRectangle, MeasureOnSuccessCallback, ScrollView, StatusBar, Text, TouchableOpacity, View } from 'react-native';
import type { MenuProps } from '.';
import { deviceHeight, deviceWidth } from '../../screen/px2dp';
// import * as utils from '../../utils/lazy';
import { hidePopoverView, showPopoverView } from '../Hud/Hud';

type State = {
}


type Reducer = (prevState: State, action: Partial<State>) => State



export default (props: MenuProps) => {

    const {
        defaultAlignHorizontal = 'left',
        defaultAlignVertical = 'bottom'
    } = props

    const [state, dispatch] = React.useReducer<Reducer>((prevState, action) => Object.assign({}, prevState, action), {})

    // const containerRef = React.useRef<{ measureInWindow: (callback: MeasureInWindowOnSuccessCallback) => void }>()
    const containerRef = React.useRef<{ measure: (callback: MeasureOnSuccessCallback) => void }>()
    const rootView = React.useRef<{
        pageX: number;
        pageY: number;
        height: number;
        width: number;
    }>({ pageX: 0, pageY: 0, width: 0, height: 0 })
    const sc = React.useRef<LayoutRectangle>({ x: 0, y: 0, width: 0, height: 0 })

    // React.useEffect(() => {
    //     ; (async () => {
    //         await utils.sleep()
    //         containerRef.current?.measure((...args) => {
    //             console.log('containerRef', args)
    //             if (args.length == 6) {
    //                 _container.current = {
    //                     x: args[4],
    //                     y: args[5],
    //                     width: args[2],
    //                     height: args[3],
    //                 }
    //             }
    //         })
    //     })()
    // })


    const getRootViewlayoutPromise = () => {
        return new Promise((resovle, reject) => {
            containerRef.current?.measure((...args) => {
                if (args.length == 6) {
                    rootView.current = {
                        width: args[2],
                        height: args[3],
                        pageX: args[4],
                        pageY: args[5],
                    }
                }
                // console.log('RootView', rootView.current)
                resovle(args)
            })
        })
    }


    const getLayoutInfos: () => {
        alignVertical: 'bottom' | 'top';
        alignHorizontal: 'left' | 'right';
        width: number;
        height: number;
        x: number;
        y: number;
        target_width: number;
        target_height: number;
    }
        = () => {
            let alignVertical: 'bottom' | 'top' = defaultAlignVertical
            let alignHorizontal: 'left' | 'right' = defaultAlignHorizontal
            let width = rootView.current.width
            let height = rootView.current.height
            let x = rootView.current.pageX
            // let y = (StatusBar.currentHeight || 0) + _container.current.y + height
            let y = rootView.current.pageY + height
            if (x > Math.abs(deviceWidth - width - x)) {
                alignHorizontal = 'right'
            }
            if (y > deviceHeight * .5) {
                alignVertical = 'top'
            }
            /**todo: target_width的获取是延迟的，所以这里又问题 */
            const target_width = sc.current.width
            const target_height = CELL_HEIGHT * (Math.min(props.data?.length || 0, 5) || 0)
            return {
                alignVertical,
                alignHorizontal,
                width,
                height,
                x,
                y,
                target_width,
                target_height,
            }
        }


    const reLayout = (): Partial<{
        left: number;
        right: number;
        top: number;
        botttom: number;
    }> => {
        let {
            alignVertical,
            alignHorizontal,
            width,
            height,
            x,
            y,
            target_width,
            target_height,
        } = getLayoutInfos()

        // console.log({ getLayoutInfos: getLayoutInfos() })
        const layout = () => {
            if (alignHorizontal == 'left') {
                if (target_width + x > deviceWidth) {
                    return {
                        left: Math.abs(deviceWidth - target_width) * .7,
                        top: y,
                    }
                }
                return {
                    left: Math.max(x, 15),
                    top: y,
                }
            } else {
                let _x = deviceWidth - x - width
                if (target_width + _x > deviceWidth) {
                    return {
                        right: Math.abs(deviceWidth - target_width) * .7,
                        top: y
                    }
                }
                return {
                    right: Math.max(_x, 15),
                    top: y
                }
            }
        }
        if (alignVertical == 'bottom') {
            y = y + PADDING
            return layout()
        } else {
            y = rootView.current.pageY - target_height - PADDING * 2 - ARROW_HEIGHT
            return layout()
        }
    }


    const PADDING = 10
    const ARROW_HEIGHT = 12
    const CELL_HEIGHT = 36


    const show = async () => {
        props.onContainerClick && props.onContainerClick()
        if (props.data == undefined || props.data?.length == 0) return
        /**重新获取rootview的定位 */
        await getRootViewlayoutPromise()
        /**重新获取rootview的定位 */
        showPopoverView({
            content: (
                <TouchableOpacity
                    activeOpacity={1}
                    style={{

                        position: 'absolute',
                        minWidth: deviceWidth * 0.36,
                        maxWidth: deviceWidth * 0.8,
                        minHeight: CELL_HEIGHT + PADDING * 2,
                        maxHeight: CELL_HEIGHT * 5 + PADDING * 2,
                        borderRadius: 6, backgroundColor: '#000000ee',
                        // overflow: 'hidden' ,
                        padding: PADDING,
                        ...reLayout()
                    }}
                >

                    <View style={{
                        width: ARROW_HEIGHT, height: ARROW_HEIGHT,
                        backgroundColor: '#000000ee', position: 'absolute', zIndex: 1,
                        transform: [{ rotateZ: '45deg' }],
                        ...(() => {
                            const {
                                alignVertical,
                                alignHorizontal,
                            } = getLayoutInfos()
                            if (alignVertical == 'bottom' && alignHorizontal == 'left') return { left: '20%', top: -5 }
                            if (alignVertical == 'bottom' && alignHorizontal == 'right') return { right: '20%', top: -5 }
                            if (alignVertical == 'top' && alignHorizontal == 'left') return { left: '20%', bottom: -5 }
                            if (alignVertical == 'top' && alignHorizontal == 'right') return { right: '20%', bottom: -5 }
                            return {}
                        })()
                    }} />

                    <ScrollView onLayout={e => {
                        // console.log('target onLayout', e.nativeEvent.layout)
                        let _sc: LayoutRectangle = e.nativeEvent.layout
                        sc.current = _sc
                    }}
                    // style={{ backgroundColor: "red" }}
                    >
                        {props.data?.map((i, idx) => {
                            return (
                                <TouchableOpacity
                                    activeOpacity={.7}
                                    key={`sg-memnu-${idx}`}
                                    style={{
                                        height: CELL_HEIGHT, display: 'flex', flexDirection: 'row', alignItems: 'center'
                                        // ,backgroundColor:utils.randomcolor()
                                    }}
                                    onPress={e => {
                                        props.onItemClick && props.onItemClick(idx, i.extra)
                                        hidePopoverView()
                                    }}
                                >
                                    {i.icon &&
                                        <Image style={{ width: 18, height: 18, marginRight: 4 }} source={i.icon} />
                                    }
                                    <Text style={{ flexShrink: 1, fontSize: 14, color: 'white' }}>{i.text}</Text>
                                </TouchableOpacity>
                            )
                        })}
                    </ScrollView>
                </TouchableOpacity>
            )
        })
    }

    return (
        <TouchableOpacity
            ref={containerRef as any}
            onPress={e => show()}
            {...props}
        />
    )
}